package org.realogic.btp.resourcefile;

import java.io.File;
import java.util.Hashtable;
import java.util.Iterator;
import java.util.regex.Pattern;

public final class KResouceFileReader {
	
	private Hashtable<String, KResouceFile> cache = new Hashtable<String, KResouceFile>(1000);
	private KResourceFileFinder ff;
	private String path;

	public KResouceFileReader(String path, Pattern fileNnamePattern) {
		this.path = path;
		ff = new KResourceFileFinder().setFileNnamePattern(fileNnamePattern).setRecursive(true).setIncludeDirs(true);
	}

	public void loadAllFirst() {
		if (cache != null && cache.isEmpty() == false) {
			cache.clear();
		}
		ff.searchPath(path);
		Iterator<File> iterator = ff.iterator();
		KResouceFile tmp = null;
		while (iterator.hasNext()) {
			File f = iterator.next();
			if (f.isFile() == true) {
				tmp = new KResouceFile(f);
				cache.put(f.getName(), tmp);
			}
		}
	}

	public KResouceFile getResouceFile(String theName) {
		KResouceFile tmpModel = null;
		String tmpName = theName;
		tmpModel = cache.get(tmpName);
		if (tmpModel == null) {
			tmpModel = loadResource(tmpName);
			if (tmpModel != null) {
				cache.put(theName, tmpModel);
			}
		}
		return tmpModel;
	}

	public void reloadResouceFile(KResouceFile theResouceFile) {
		// cache.remove(theResouceFile.getResouce().getName());
		theResouceFile.setResouce(new File(theResouceFile.getResouce().getPath()));
	}

	private KResouceFile loadResource(String aFileName) {
		ff.searchPath(path);
		Iterator<File> iterator = ff.iterator();
		KResouceFile tmp = null;
		while (iterator.hasNext()) {
			File f = iterator.next();
			if (f.isFile() == true) {
				if (f.getName().equalsIgnoreCase(aFileName)) {
					tmp = new KResouceFile(f);
				}
			}
		}
		return tmp;
	}

}
